import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_device_info_plugin/flutter_device_info_plugin.dart';
import 'package:furaha_mkopo/cache/fm_cache_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_report_event_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_toast.dart';
import 'package:furaha_mkopo/launch/fm_dynamic_test_api.dart';
import 'package:furaha_mkopo/manager/fm_global_manager.dart';
import 'package:furaha_mkopo/manager/fm_init_manager.dart';
import 'package:furaha_mkopo/manager/fm_location_manager.dart';
import 'package:furaha_mkopo/net/fm_http_manager.dart';
import 'package:furaha_mkopo/net/fm_http_response.dart';
import 'package:furaha_mkopo/net/fm_net_param_manager.dart';
import 'package:furaha_mkopo/page/dialog/address/entity/fm_address_entity.dart';
import 'package:furaha_mkopo/page/dialog/address/fm_address_api.dart';
import 'package:get/get.dart';
import '../commonTool/fm_route_tool.dart';
import '../commonUI/fm_progress_hud.dart';
import '../init/fm_init_model.dart';
import '../manager/fm_net_monitor_manager.dart';
import '../page/dialog/address/fm_address_api.dart';
import '../page/tab/fm_tab_page.dart';
import '../welcome/fm_welcome_page.dart';
import 'fm_init_api.dart';

class FMLaunchController extends GetxController {

  final FMNetMonitorManager netMonitorManager = FMNetMonitorManager();

  BuildContext? buildContext;

  bool _isFirstLoad = false;

  bool isRefreshing = false;

  bool _serverUrlExecute = false;

  @override
  void onInit() {
    super.onInit();

    FMProgressHud.showLoading();

    requestDynamicUrl();

    startNetMonitor();
  }

  @override
  void onClose() {
    netMonitorManager.dispose();
    super.onClose();
  }

  void refreshData() {
    isRefreshing = true;
    Future.delayed(const Duration(milliseconds: 100),(){
      FMInitApi api = FMInitApi();
      api.send<FMInitModel,FMInitModel>(decodeType: FMInitModel()).then((value){
        FMProgressHud.hideLoading();

        isRefreshing = false;
        if (value.code == 0) {
          FMInitManager().initModel = value.data;

          // FMNetParamManager().setActual(value.data?.lang.toString());
          
          reportFaceBook(value.data?.thronged);
          
          jumpController();

          reportData();
        }else {
          if (!_isFirstLoad) {
            _isFirstLoad = true;
          }else {
            FMToast.showText("Network request error");
          }
        }
      });
      FMAddressApi addressApi = FMAddressApi();
      addressApi.send().then((value){
        if(value.data != null){
          FMCacheTool.saveAddressList(jsonEncode(value.data!));
        }
      });
    });
  }

  void startNetMonitor() async {
    netMonitorManager.init();
    netMonitorManager.connectionStatusStream.listen((status) {
      if (needRefreshData(status) && _serverUrlExecute) {
        Future.delayed(const Duration(milliseconds: 500),(){
          if (!isRefreshing) {
            FMProgressHud.showLoading();
            refreshData();
          }
        });
      }else {
        FMProgressHud.hideLoading();
      }
    });
  }

  void tryClick() {
    FMProgressHud.showLoading();
    requestDynamicUrl();
  }

  bool needRefreshData(bool status) {
    return status && FMInitManager().initModel == null;
  }

  void reportFaceBook(FMInitThrongedModel? initThrongedModel) {
    FlutterDeviceInfoPlugin().reportFaceBook(
        initThrongedModel?.embrace,
        initThrongedModel?.fond,
        initThrongedModel?.drew,
        initThrongedModel?.smiled
    );
  }

  void jumpController() {
    bool flag = FMCacheTool.welcomePageFlag();

    BuildContext context = FMGlobalManager().context!;

    if (!flag) {
      FMRouteTool.pushReplacement(context, const FMWelcomePage());
    }else {
      FMRouteTool.pushReplacement(context, const FMTabPage());
    }
  }

  void reportData() {
    FMReportEventTool.reportLocation();
    FMReportEventTool.reportDevice();
  }

  void requestDynamicUrl() {
    _serverUrlExecute = false;
    FMHttpManager.getInstance().dynamicServerUrl((isSuccess,urls,message) async {
      if(isSuccess){
        for (var element in urls) {
          if(element.isEmpty) continue;
          FMDynamicTestApi testApi = FMDynamicTestApi(element);
          FMHttpResponse response = await testApi.send();
          if(response.code != 0 || response.data == null){
            continue;
          }
          FMNetParamManager().baseDomain = element;
          _serverUrlExecute = true;
          refreshData();
          break;
        }
      }
    });
  }

}